package com.common;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;

public class EasyExcelUtils {

	public static void writeWithoutHead() throws IOException {
		try (OutputStream out = new FileOutputStream("d://withoutHead.xlsx");) {
			ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, false);
			Sheet sheet1 = new Sheet(1, 0);
			sheet1.setSheetName("sheet1");
			List<List<String>> data = new ArrayList<>();
			for (int i = 0; i < 100; i++) {
				List<String> item = new ArrayList<>();
				item.add("item0" + i);
				item.add("item1" + i);
				item.add("item2" + i);
				data.add(item);
			}
			writer.write0(data, sheet1);
			writer.finish();
		}
	}

	public static void write(List<Map<String, Object>> list, String path) throws IOException {
		try (OutputStream out = new FileOutputStream(path)) {
			ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, false);
			Sheet sheet1 = new Sheet(1, 0);
			sheet1.setSheetName("sheet1");
			List<List<String>> data = new ArrayList<>();
			for (Map<String, Object> map : list) {
				List<String> item = new ArrayList<>();
				for (Map.Entry<String, Object> entry : map.entrySet()) {
					if (entry.getValue() == null) {
						item.add("");
					} else {
						item.add(entry.getValue().toString());
					}
				}
				data.add(item);
			}
			writer.write0(data, sheet1);
			writer.finish();
		}
	}

	public static List<List<String>> getData(List<HashMap<String, Object>> list) {
		List<List<String>> data = new ArrayList<>();
		for (Map<String, Object> map : list) {
			List<String> item = new ArrayList<>();
			for (Map.Entry<String, Object> entry : map.entrySet()) {
				if (entry.getValue() == null) {
					item.add("");
				} else {
					item.add(entry.getValue().toString());
				}
			}
			data.add(item);
		}
		return data;
	}

	public static void write(OutputStream out, List<HashMap<String, Object>> list) {
		ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, false);
		Sheet sheet1 = new Sheet(1, 0);
		sheet1.setSheetName("sheet1");
		writer.write0(getData(list), sheet1);
		writer.finish();
	}

	public static void write0(OutputStream out, List<List<String>> list) {
		ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, false);
		Sheet sheet1 = new Sheet(1, 0);
		sheet1.setSheetName("sheet1");
		writer.write0(list, sheet1);
		writer.finish();
	}
}
